package icu.nil.demo.shell.websocket

import icu.nil.demo.shell.config.USER_UUID_KEY
import icu.nil.demo.shell.config.logger
import icu.nil.demo.shell.service.WebSSHService
import org.springframework.stereotype.Component
import org.springframework.web.socket.*


/**
 * Create by xiangliyou on 2020/3/10 16:53.
 * email: xiangliyou@aliyun.com
 * Des:  WebSSH的WebSocket处理器
 */
@Component
class WebSSHWebSocketHandler(
        private val webSSHService: WebSSHService
) : WebSocketHandler {


    override fun afterConnectionEstablished(session: WebSocketSession) {
        logger().info("用户:{},连接WebSSH", session.attributes[USER_UUID_KEY] ?: "USER_UUID_KEY is null")
        //调用初始化连接
        webSSHService.initConnection(session)
    }

    override fun handleMessage(session: WebSocketSession, message: WebSocketMessage<*>) {
        when (message) {
            is TextMessage -> {
                logger().info("用户:{},发送命令:{}", session.attributes[USER_UUID_KEY] ?: "", message.payload)
                //调用service接收消息
                webSSHService.recvHandle(message.payload, session)
            }
            is BinaryMessage -> {
            }
            is PongMessage -> {
            }
            else -> {
                logger().warn("Unexpected WebSocket message type: $message")
            }
        }
    }

    override fun handleTransportError(session: WebSocketSession, exception: Throwable) {
        logger().error("handleTransportError")
    }

    override fun afterConnectionClosed(session: WebSocketSession, closeStatus: CloseStatus) {
        webSSHService.close(session)
    }


    override fun supportsPartialMessages(): Boolean {
        return false
    }
}